package com.maple.p2pclient.http;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public abstract class BaseRetrofitClient {
    protected abstract OkHttpClient.Builder generateOkHttpBuilder(OkHttpClient.Builder builder);

    protected Retrofit.Builder generateRetrofitBuilder(Retrofit.Builder builder) {
        return builder;
    }

    public <T> T getApiService(
            Class<T> service,
            String baseUrl,
            boolean useDefaultGsonConverterFactory
    ) {
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(generateOkHttpBuilder(new OkHttpClient.Builder()).build());

        if (useDefaultGsonConverterFactory) {
            // 默认添加对Gson的支持
            Gson gson = new GsonBuilder().create();
            retrofitBuilder.addConverterFactory(GsonConverterFactory.create(gson));
        }

        return generateRetrofitBuilder(retrofitBuilder)
                .build()
                .create(service);
    }

    // Overload for default MoshiConverterFactory usage
    public <T> T getApiService(Class<T> service, String baseUrl) {
        return getApiService(service, baseUrl, true);
    }
}
